package org.csu.petstore_manage.controller;

import com.alibaba.fastjson.JSON;
//import com.sun.deploy.net.HttpResponse;
//import com.sun.org.apache.bcel.internal.generic.NEW;
import org.csu.petstore_manage.domain.*;
import org.csu.petstore_manage.service.AccountService;
import org.csu.petstore_manage.service.CatalogService;
import org.csu.petstore_manage.service.OrderService;
import org.csu.petstore_manage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping(value = "/jpetstore",produces = "application/json; charset=utf-8")
@SessionAttributes({"account","userList","orderList"})
public class manageController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private CatalogService productService;
    @Autowired
    private CatalogService updateproductService;

    private static final List<String> LANGUAGE_LIST;
    private static final List<String> CATEGORY_LIST;
    private static final List<String> CARD_LIST;

    static {
        List<String> langList = new ArrayList<String>();
        langList.add("ENGLISH");
        langList.add("CHINESE");
        LANGUAGE_LIST = Collections.unmodifiableList(langList);

        List<String> catList = new ArrayList<String>();
        catList.add("FISH");
        catList.add("DOGS");
        catList.add("REPTILES");
        catList.add("CATS");
        catList.add("BIRDS");

        CATEGORY_LIST = Collections.unmodifiableList(catList);

        List<String> cardList = new ArrayList<String>();
        cardList.add("Visa");
        cardList.add("MasterCard");
        cardList.add("American Express");
        CARD_LIST = Collections.unmodifiableList(cardList);
    }
    @PostMapping("/edit")
    public void editProduct(String phone,HttpServletResponse response) throws Exception {


        System.out.println("xiugai");
    }
    @GetMapping("/getCode")
    public void getCode(String phone,HttpServletResponse response) throws Exception {

        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
       //Sample s=new Sample();
        Sample.send(phone,verifyCode);
            PrintWriter out = response.getWriter();
        System.out.println(verifyCode);
            out.print(verifyCode);
            out.flush();
            out.close();


    }
    @GetMapping("/find")
    public void find(String email,HttpServletResponse response) throws IOException, MessagingException {

        String result;
        String password = accountService.findPassWord(email);
        if (password==null){
            PrintWriter out = response.getWriter();
            result = "失败";
            out.print("fail");
            out.flush();
            out.close();
        }else {
            PrintWriter out = response.getWriter();
            result = "成功";
            out.print("success");
            out.flush();
            out.close();
        }
    }
    @GetMapping("/signup")
    public void signup(String username, String password, String email,
                       String truecode,String code,String phone, HttpSession session, HttpServletResponse response) throws IOException {
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        account.setEmail(email);
        account.setPhone(phone);
        System.out.println("email"+email);
        System.out.println(truecode);
        System.out.println(code);
        //session.setAttribute("account",account);
        String result;
        Account checkAccount = accountService.getAccount(username);
        if (checkAccount!=null||!truecode.equals(code)){
            PrintWriter out = response.getWriter();
            result = "失败";
            out.print("fail");
            out.flush();
            out.close();
        }else {
            accountService.insertAccount(account);
            PrintWriter out = response.getWriter();
            result = "成功";
            out.print("success");
            out.flush();
            out.close();
        }
        System.out.println("请求登录状态: "+result+" 账号: "+username);
    }

    @GetMapping("/checklogin")
    public void checkin(String username, String password, HttpSession session, HttpServletResponse response) throws IOException {
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        //session.setAttribute("account",account);
        String result;
        //Account checkAccount = accountService.getAccount(username,password);
        if (false){
            PrintWriter out = response.getWriter();
            result = "失败";
            out.print("fail");
            out.flush();
            out.close();
        }else {
            PrintWriter out = response.getWriter();
            result = "成功";
            out.print("success");
            out.flush();
            out.close();
        }

        System.out.println("请求登录状态: "+result+" 账号: "+username);
    }
    @GetMapping("/index")
    public String index(){
        return "index";
    }
    @GetMapping("/main")
    public String main(){
        return "catalog/main";
    }
    @GetMapping("/profile")
    public String profile(){
        return "catalog/profile";
    }
    @GetMapping("/order")
    public String order(Model model){
        List<Order> orderList = orderService.getOrders();
        model.addAttribute("orderList",orderList);
        model.addAttribute("updateOrder",new Order());
        model.addAttribute("CARD_LIST",CARD_LIST);
        return "catalog/order";
    }
    @GetMapping("/user")
    public String user(Model model){
        List<User> userList = userService.getUsers();
        model.addAttribute("userList",userList);
        model.addAttribute("updateUser",new User());
        model.addAttribute("LANGUAGE_LIST",LANGUAGE_LIST);
        return "catalog/user";
    }
    @GetMapping("/product")
    public String product(Model model){
        System.out.println("getproducts");
        List<Product> productList=productService.getProducts();
       // List<Product> productList=productService.getProducts();
        System.out.println(productList.get(0));
        model.addAttribute("productList",productList);
        model.addAttribute("updateProduct",new Product());
        model.addAttribute("updateItem",new Item());
        model.addAttribute("CARD_LIST",CARD_LIST);
        return "catalog/jqgrid";
    }

    @PostMapping("/updateuser")
    public String updateUser(User updateUser){
        userService.updateUser(updateUser);
        return "redirect:/jpetstore/user";
    }

    @GetMapping("/deleteuser")
    public void deleteUser(String username, HttpServletResponse response) throws IOException {
        User user = new User();
        user.setUsername(username);
        userService.deleteUser(user);
        PrintWriter out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();

    }
    @GetMapping("/getOrder")
    public void getOrder(String orderId, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        Order order = orderService.getOrder(Integer.parseInt(orderId));
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(order));
        out.flush();
        out.close();
    }

    @GetMapping("/deleteorder")
    public void deleteOrder(String orderId, HttpServletResponse response) throws IOException {

        orderService.deleteOrder(Integer.parseInt(orderId));
        PrintWriter out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();

    }

    @PostMapping("/updateorder")
    public String updateOrder(Order updateOrder){
        orderService.updateOrder(updateOrder);
        return "redirect:/jpetstore/order";
    }


    @GetMapping("/getitems")
    public void getItems(String productId,HttpServletResponse response) throws IOException {
        List<Item> items = catalogService.getItemListByProduct(productId);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(items));
        out.flush();
        out.close();
  //      model.addAttribute("items",items);
    }


    @PostMapping("/addcategory")
    public String addCategory(HttpServletRequest request){
        System.out.println("addcatrgroy");
        String categoryId = request.getParameter("categoryId");
        String categoryName = request.getParameter("categoryName");
        String categoryDescn = request.getParameter("categoryDescn");
        catalogService.addCategory(categoryId,categoryName,categoryDescn);
        return "redirect:/jpetstore/product";
    }

    @GetMapping("/getcategory")
    public void getCategory(HttpServletResponse response) throws IOException {
        List<Category> categories = catalogService.getCategoryList();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(categories));
        out.flush();
        out.close();
    }
    @GetMapping("/getproducts")
    public void getproducts(HttpServletResponse response) throws IOException {
        List<Product> products = catalogService.getProducts();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(products));
        out.flush();
        out.close();
    }

    @PostMapping("/addproduct")
    public String addProduct(HttpServletRequest request){
        System.out.println("aproduct");

        String productId = request.getParameter("productId");
        String categoryId = request.getParameter("categoryId");
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        System.out.println(productId+categoryId+name+description);
       Product newProduct = new Product();
        newProduct.setCategoryId(categoryId);
        newProduct.setProductId(productId);
        newProduct.setName(name);
       newProduct.setDescription(description);
        catalogService.addProduct(newProduct);
       return "redirect:/jpetstore/product";
    }
    @PostMapping("/additem")
    public String addItem(HttpServletRequest request){
        System.out.println("additem");
        String productId=request.getParameter("productId");
        String itemId = request.getParameter("itemId");
        String unitcost = request.getParameter("unitcost");
        String listprice = request.getParameter("listprice");
        String supplier = request.getParameter("supplier");
        String status = request.getParameter("status");
        String attr = request.getParameter("attr");
        String quantity = request.getParameter("quantity");
        Item item = new Item();
        item.setProductId(productId);
        item.setItemId(itemId);
        item.setListPrice(new BigDecimal(listprice));
        item.setUnitCost(new BigDecimal(unitcost));
        item.setSupplierId(Integer.parseInt(supplier));
        item.setStatus(status);
        item.setAttribute1(attr);
        item.setQuantity(Integer.parseInt(quantity));
        catalogService.addItem(item);
        return "redirect:/jpetstore/product";
    }
    @PostMapping("/updateproduct")
    public String updateProduct(Product updateProduct){

        List<Product> productList=productService.getProducts();
        System.out.println(productList.get(0));
        productService.updateProduct(updateProduct);
       // List<Product> productList=productService.getProducts();
       // model.addAttribute("productList",productList);
        List<Product> productLis=productService.getProducts();
        System.out.println(productLis.get(0));
        List<Product> productLi=productService.getProducts();
        System.out.println(productLi.get(0));
        List<Product> productL=productService.getProducts();
        System.out.println(productL.get(0));
        List<Product> product=productService.getProducts();
        System.out.println(product.get(0));

        return "redirect:/jpetstore/product";

    }
    @PostMapping("/updateitem")
    public String updateItem(Item updateItem){

        catalogService.updateItem(updateItem);

        return "redirect:/jpetstore/product";

    }

    @GetMapping("/getProduct")
    public void getProduct(String productId, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        Product product=catalogService.getProduct(productId);
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(product));
        out.flush();
        out.close();
    }
    @GetMapping("/getitem")
    public void getItem(String itemId, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        Item item=catalogService.getItem(itemId);
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(item));
        out.flush();
        out.close();
    }

    @GetMapping("/deleteproduct")
    public void deleteProduct(String productId, HttpServletResponse response) throws IOException {

        catalogService.deleteProduct(productId);
        PrintWriter out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();

    }
    @GetMapping("/deleteitem")
    public void deleteItem(String itemId, HttpServletResponse response) throws IOException {

        catalogService.deleteItem(itemId);
        PrintWriter out = response.getWriter();
        out.print("success");
        out.flush();
        out.close();

    }
}
